import os, sys, re

FORBIDEN = re.compile(".*\.hg.*")

ESC_DIR = "@DIR@"

def execechdir(
		path,
		cmd
	):
	if FORBIDEN.match(path):
		print "FORBIDEN: " + path
		return
	if not os.path.isfile(path):
		os.system(cmd.replace(ESC_DIR, path))
		for s in os.listdir(path):
			sp = os.path.join(path, s)
			execechdir(
				sp,
				cmd
			)

if __name__ == "__main__":
	rootdir = "."
	if len(sys.argv) > 2:
		rootdir = sys.argv[2]

	cmd = sys.argv[1]
	i = 3
	while i < len(sys.argv):
		src = sys.argv[i]
		dst = sys.argv[i+1]
		cmd = cmd.replace(src, dst)
		i += 2
		
	execechdir(rootdir, cmd)